package com.zhy.sunmi.fragment.sell;

import android.app.DatePickerDialog;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.greendao.gen.SellGoodHistoryDao;
import com.zhy.greendao.gen.SoldGoodDetailDao;
import com.zhy.sunmi.MyApplication;
import com.zhy.sunmi.PrintUtil4;
import com.zhy.sunmi.R;
import com.zhy.sunmi.bean.SellGoodHistory;
import com.zhy.sunmi.bean.SoldGoodDetail;
import com.zhy.sunmi.utils.ScreenUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import static com.zhy.sunmi.MyApplication.pos_usb;
import static com.zhy.sunmi.utils.PrintUtil.cutPaper;
import static com.zhy.sunmi.utils.PrintUtil.printBar;
import static com.zhy.sunmi.utils.PrintUtil.printText;


public class SubSalesHistoryFragment extends Fragment {
    private View rootView;
    private TextView tv;
    private TextView tv_number;
    private RecyclerView recyclerView;

    private SellGoodHistoryDao sellGoodHistoryDao = MyApplication.getDaoSession().getSellGoodHistoryDao();
    private SoldGoodDetailDao soldGoodDetailDao = MyApplication.getDaoSession().getSoldGoodDetailDao();
    private Spinner spinner1;
    private List<SellGoodHistory> sellGoodHistories = new ArrayList<>();
    private List<String> curs = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_sub_sales_history, container, false);
            initView(rootView);
        } else {

        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }


        return rootView;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void initView(View view) {
        spinner1 = view.findViewById(R.id.sp_view1);
        curs.addAll(Arrays.asList(getResources().getStringArray(R.array.shipping_type)));
        setCursListener(0, true);
        tv_number = view.findViewById(R.id.tv_show_number);

//        tv_number.setOnClickListener(v -> {
////            showDatePick(1);
//
//            DatePickerDialog datePickerDialog = new DatePickerDialog(getContext());
//
//
//            datePickerDialog.show();
//
//            datePickerDialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);
//        });


        SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy, HH:mm", Locale.ENGLISH);
        recyclerView = view.findViewById(R.id.recyclerView2);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(new CommonAdapter<SellGoodHistory>(getContext(), R.layout.item_sell_history2, sellGoodHistories) {

            @Override
            protected void convert(ViewHolder holder, SellGoodHistory sellGoodHistory, int position) {
                if (sellGoodHistory.getOrderCode().toString().equals("")) {
                    holder.setText(R.id.tv2, "-");
                } else {
                    holder.setText(R.id.tv2, sellGoodHistory.getOrderCode());
                }

                holder.setText(R.id.tv1, sdf.format(new Date(sellGoodHistory.getPayTime() * 1000)));
                if (sellGoodHistory.getCustomerCode().toString().equals("")) {
                    holder.setText(R.id.tv3, "-");
                } else {
                    holder.setText(R.id.tv3, sellGoodHistory.getCustomerCode());
                }

                holder.setText(R.id.tv4, sellGoodHistory.getCashierId() + "");
                holder.setText(R.id.tv5, sellGoodHistory.getTotalMoneyAfterDiscount());
                //支付状态（0 支付完成；1 Cancel；2 Void；3 Hold 4 Refund 5 去支付）
                String status = "";
                switch (sellGoodHistory.getPayStatus()) {
                    case 0:
                        status = "Sold";
                        break;
                    case 1:
                        status = "Cancel";
                        break;
                    case 2:
                        status = "Void";
                        break;
                    case 3:
                        status = "Hold";
                        break;
                    case 4:
                        status = "Refund";
                        break;

                }


                holder.setText(R.id.tv61, status);

                holder.setOnClickListener(R.id.iv_edit, v -> {
                    showDialog(sellGoodHistory);
                });

            }
        });

        initSearchView(view);

    }

    private void initSearchView(View view) {

        TextView tv = view.findViewById(R.id.tv_search);
        tv.setOnClickListener(v -> {
//            MyApplication.getDaoSession().clear();
            List<SellGoodHistory> sellGoodHistories2 = sellGoodHistoryDao.queryBuilder().where(SellGoodHistoryDao.Properties.PayStatus.eq(spinner1.getSelectedItemId())).orderDesc(SellGoodHistoryDao.Properties.PayTime).list();
            for(SellGoodHistory s:sellGoodHistories2){
                s.getSoldGoodDetails();
            }

            tv_number.setText("Showing  " + sellGoodHistories2.size() + " sales");
            sellGoodHistories.clear();
            sellGoodHistories.addAll(sellGoodHistories2);
            recyclerView.getAdapter().notifyDataSetChanged();
        });
    }


    private void showDialog(SellGoodHistory sellGoodHistory) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_history_detail, null, false);
        final AlertDialog dialog = new AlertDialog.Builder(getContext()).setView(view).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        //此处设置位置窗体大小，我这里设置为了手机屏幕宽度的3/4  注意一定要在show方法调用后再写设置窗口大小的代码，否则不起效果会
        dialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);
        TextView tv_refund = view.findViewById(R.id.tv_refund);
        TextView tv_carry = view.findViewById(R.id.tv_carry);
        TextView tv_print = view.findViewById(R.id.tv_print);

        switch (sellGoodHistory.getPayStatus()) {
            case 0:

                tv_carry.setVisibility(View.GONE);
                break;
            case 1:

                tv_carry.setVisibility(View.GONE);
                tv_refund.setVisibility(View.GONE);
                break;
            case 2:
                tv_carry.setVisibility(View.GONE);
                tv_refund.setVisibility(View.GONE);
                break;
            case 3:
                tv_refund.setVisibility(View.GONE);
                break;
            case 4:
                tv_carry.setVisibility(View.GONE);
                tv_refund.setVisibility(View.GONE);
                break;

        }


        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        tv_confirm.setOnClickListener(v -> {
            dialog.dismiss();
        });

        view.findViewById(R.id.tv_cancel).setOnClickListener(v -> {
            dialog.dismiss();
        });

        tv_print.setOnClickListener(v -> {
            print(sellGoodHistory);
        });


        tv_carry.setOnClickListener(v -> {
            carryOn(sellGoodHistory);
            dialog.dismiss();
        });

        tv_refund.setOnClickListener(v -> {
            refundOn(sellGoodHistory);
            dialog.dismiss();
        });


        List<SoldGoodDetail> soldGoodDetails = sellGoodHistory.getSoldGoodDetails();
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(new CommonAdapter<SoldGoodDetail>(getContext(), R.layout.item_selling_good, soldGoodDetails) {

            @Override
            protected void convert(ViewHolder holder, SoldGoodDetail sellingGood, int position) {
                holder.setText(R.id.selling_number, sellingGood.getNumber() + "");
                holder.setVisible(R.id.iv_ljt, false);
                holder.setText(R.id.tv_good_disoff, new Double(sellingGood.getDiscount()).intValue() + "%");



                holder.setText(R.id.tv_selling_money, "£" +  BigDecimal.valueOf(sellingGood.getTotalPrice()).setScale(2, BigDecimal.ROUND_DOWN).toString());
                holder.setText(R.id.tv_goodname, sellingGood.getEnglishName());
                holder.setText(R.id.tv_goodCname, sellingGood.getChineseName());

            }
        });


    }

    private void carryOn(SellGoodHistory sellGoodHistory) {
        SellFragment sellFragment = (SellFragment) getParentFragment();
        sellFragment.changeFragment(0, 0, sellGoodHistory);
    }

    private void refundOn(SellGoodHistory sellGoodHistory) {

        SellFragment sellFragment = (SellFragment) getParentFragment();
        sellFragment.changeFragment(0, 2, sellGoodHistory);
    }


    private void print(SellGoodHistory sellGoodHistory) {
        if (pos_usb == null) {
            Toast.makeText(MyApplication.getInstance().getApplicationContext(), "Please connect the printer", Toast.LENGTH_LONG).show();
            return;
        }


        List<SoldGoodDetail> soldGoodDetailList = sellGoodHistory.getSoldGoodDetails();

        String orderCode = sellGoodHistory.getOrderCode();
        String giveCash = sellGoodHistory.getActualPayMoney();
        String changestr = sellGoodHistory.getChangeMoney();
        SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy, HH:mm:ss", Locale.ENGLISH);
        String time = sdf.format(new Date(sellGoodHistory.getPayTime() * 1000));

        String a = PrintUtil4.printxx(soldGoodDetailList);

        String status = "";
        switch (sellGoodHistory.getPayStatus()) {
            case 0:
                status = "Sold";
                break;
            case 1:
                status = "Cancel";
                break;
            case 2:
                status = "Void";
                break;
            case 3:
                status = "Hold";
                break;
            case 4:
                status = "Refund";
                break;
            case 5:
//                status = "Refund";
                break;
        }

        String payMethod = "";
        switch (sellGoodHistory.getPaymentMethod()) {
            case 0:
//                payMethod = "Cash";
                break;
            case 1:
                payMethod = "Cash";
                break;
            case 2:
                payMethod = "Card";
                break;
            case 3:
                payMethod = "Alipay";
                break;
            case 4:
                payMethod = "Wechat";
                break;
            case 5:
//                status = "Refund";
                break;
        }


        printText("------------" + status + "-----------", 1, 1, 20);

        if(!TextUtils.isEmpty(sellGoodHistory.getCustomerCode())){
            printText(2,"Table"+sellGoodHistory.getCustomerCode(), 1, 1, 20);
        }
//        printText(2,"Table"+sellGoodHistory.getCustomerCode(), 1, 1, 20);
        printText("Golden Mayfair Chinese Restaurant", 1, 1, 20);
        printText("3 West Road", 1, 0, 20);
        printText("Westcliff-on-Sea, Essex,SS0 9AU", 1, 0, 20);
        printText("Telephone 01702352707", 1, 0, 20);
        printText("", 0, 0);
        printText("Order Ref: " + orderCode, 0, 1);
        printText("------------------------------------------", 0, 0);
//            printText("Description                          Total", 0, 0);
//            printText("------------------------------------------", 0, 0);
        printText(a, 0, 0);
        printText("Total                                " + sellGoodHistory.getTotalMoney(), 0, 0);
        printText("------------------------------------------", 0, 0);
//        printText("YOU SAVED  " + sellGoodHistory.getTotalSave(), 1, 1, 10);
//        printText("------------------------------------------", 0, 0);
        printText("Grand Total                          " + sellGoodHistory.getTotalMoneyAfterDiscount(), 0, 1);
        printText("------------------------------------------", 0, 0);
        printText("Number Of Items                        " + sellGoodHistory.getTotalNumber() + "\n", 0, 1);
        printText("VAT Summary Breakdown", 1, 3, 30);
        printText("Total      VAT Value", 1, 1, 20);
        printText(sellGoodHistory.getTotalMoneyAfterDiscount() + "         " + sellGoodHistory.getTotalVat(), 1, 0, 20);
        printText("Payment Details\n", 0, 3);
//        printText("Paid By Cash                         " + giveCash, 0, 1, 20);
        printText("Paid By "+payMethod+"                         "+ giveCash, 0, 1, 20);
        printText("Change                               " + changestr, 0, 1, 20);
        printText("You have been Served By" + MyApplication.UserName, 1, 0, 20);
        printText("Till No:" + "Till"+MyApplication.getInstance().getMachineId(), 0, 1, 10);
        printText("", 1, 1, 10);
        if (orderCode != null && !orderCode.equals("")) {
            printBar(orderCode);
        }

        printText(time, 1, 1, 20);
        printText("Please Keep for your records", 1, 0, 20);
        printText("Published Terms and Conditions Apply", 1, 0, 20);


        cutPaper();
    }


    private void setCursListener(int select, boolean monitor) {

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getBaseContext(), R.layout.myspinner, curs);
        spinner1.setAdapter(adapter);
        spinner1.setSelection(select);
        if (monitor) {
            spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                    TextView tv = (TextView) view;
                    tv.setTextColor(getResources().getColor(R.color.blueblack));    //设置颜色

                    tv.setTextSize(12f);    //设置大小

                    tv.setGravity(Gravity.LEFT);   //设置居中

                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });
        }
    }


    public void goShopping(int i, SellGoodHistory sellGoodHistory, String a) {
        sellGoodHistories.clear();
        recyclerView.getAdapter().notifyDataSetChanged();
    }

}